package com.hngs.advice;

import cn.hutool.json.JSONUtil;
import com.hngs.dto.ResponseDto;
import com.hngs.exception.BizException;
import com.hngs.info.PageInfo;
import com.hngs.threadlocal.LocalPageUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;

@RestControllerAdvice  //针对控制层返回得数据进行增强
public class MyResponseAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
       //代表对哪些方法进行增强 默认是不增强
        return true;
    }
    //报错得信息
    @ExceptionHandler
    public Object proException(Exception ex){
        if(ex instanceof BizException){
            BizException bizException=(BizException)ex;
            return ResponseDto.error(bizException.getCode(),ex.getMessage());
        }
        ResponseDto dto=ResponseDto.error(88, ex.getMessage());
        return dto;
    }


    @Override
    public Object beforeBodyWrite(Object bady,
                                  MethodParameter methodParameter,
                                  MediaType mediaType,
                                  Class<? extends HttpMessageConverter<?>> aClass,
                                  ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {
        //解决双重响应消息体
        if(bady instanceof ResponseDto){
            return bady;
        }

        ResponseDto dto=ResponseDto.success(bady);
        PageInfo pageInfo= LocalPageUtils.get();
        if(pageInfo!=null){
            HashMap<Object,Object> map=new HashMap<>();
            map.put("total",pageInfo.getTotal());
            map.put("items",bady);
            dto = ResponseDto.success(map);
            LocalPageUtils.remove();
        }


        //首先 我需要证明我是string类型得
        if (aClass == StringHttpMessageConverter.class){
            //改成json串类型
            return JSONUtil.toJsonStr(dto);
        }

        return dto;
    }
}
